<template>
  <div class="home">
    <el-container>
      <el-header class="hero">
        <h1>欢迎来到 English All In One</h1>
        <p>您的英语学习综合解决方案</p>
      </el-header>

      <el-main class="content">
        <div v-if="loading">
          <el-skeleton :rows="5" animated />
        </div>
        <div v-else-if="error">
          <el-alert :title="error" type="error" show-icon :closable="false" />
        </div>
        <div class="courses-section" v-else>
          <h2>可用课程</h2>
          <div v-if="courses.length === 0">
            <el-empty description="No courses available at the moment" />
          </div>
          <div v-else class="all-categories">
            <div v-for="category in courses" :key="category.categoryName">
              <el-divider content-position="left">
                <template #default>
                  <span class="category-name">
                    {{ category.categoryName }}
                  </span>
                </template></el-divider>
              <div class="courses-grid">
                <el-card v-for="course in category.courses" :key="course.id"
                  :class="'course-card course-card-' + (Math.floor(Math.random() * 15) + 1)"
                  @click="$router.push(`/course/${course.id}`)" shadow="hover">
                  <template #header>
                    <div class="course-header">
                      <span class="course-title">{{ course.title }}</span>
                    </div>
                  </template>
                  <div class="course-content" :style="getPercentageStyle(course)">
                    <div v-if="course.description" class="course-description">
                      {{ course.description }}
                    </div>
                    <!-- <div class="course-meta">
                    <el-tag type="success">{{ course.lessonCount }} lessons</el-tag>
                  </div> -->
                    <!-- <div class="card-footer">
                      <el-button type="primary" @click="$router.push(`/course/${course.id}`)">
                        查看课程
                      </el-button>
                    </div> -->
                  </div>
                </el-card>
              </div>
            </div>
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import http from '@/utils/http'
import { isLoggedIn } from '@/utils/auth'
import { ElContainer, ElDivider, ElHeader, ElMain, ElSkeleton, ElAlert, ElEmpty, ElCard, ElTag, ElButton, ElProgress } from 'element-plus'

export default {
  name: 'Home',
  components: {
    ElContainer,
    ElHeader,
    ElMain,
    ElSkeleton,
    ElAlert,
    ElEmpty,
    ElCard,
    ElTag,
    ElButton,
    ElProgress,
    ElDivider
  },
  data() {
    return {
      courses: [],
      loading: true,
      error: null,
      loggedIn: isLoggedIn(),
    }
  },
  async mounted() {
    await this.loadCourses()
  },
  methods: {
    getPercentageStyle(course) {
      if (course.progress !== undefined && this.loggedIn) {
        const percentageStart = this.getPercentage(course.progress.completion_percentage);
        if(percentageStart === 0) return '';
        let style = 'background: linear-gradient(to right, lightgreen ' + percentageStart + '%, transparent ' + percentageStart + '%, #66ff6633 ' + percentageStart + '%, #66ff6633 100%); ';
        style+='border: 1px solid #ffffff33;';
        return style;
      }
      return '';
    },
    getPercentage(percentage) {
      if (percentage > 0 && percentage < 1.0) {
        return 1.0;
      } else if (percentage > 99.0 && percentage < 100.0) {
        return 99.0;
      }
      return Math.round(percentage);
    },
    async loadCourses() {
      try {
        const response = await http.get('/courses')
        this.courses = response

        if (!isLoggedIn()) {
          this.loading = false;
          return;
        }
        const progressResponse = await http.get(`/progress/courses`)
        // Get lesson count for each course
        for (const category of this.courses) {
          for (let i = 0; i < category.courses.length; i++) {
            const course = category.courses[i]
            try {
              const lessonsResponse = await http.get(`/courses/${course.id}/lessons`)
              course.lessonCount = lessonsResponse.length

              if (!isLoggedIn()) {
                this.loading = false;
                return;
              }
              // Get progress for each course
              try {
                const progressData = progressResponse.find(p => p.course_id === course.id)
                if (progressData) {
                  course.progress = progressData
                }
                else {
                  course.progress = {
                    course_id: course.id,
                    lesson_id: null,
                    completed_lessons: 0,
                    completion_percentage: 0
                  }
                }
              } catch (progressErr) {
                console.warn(`Failed to load progress for course ${course.id}:`, progressErr)
              }
            } catch (err) {
              course.lessonCount = 0
            }
          }
        }

        this.loading = false
      } catch (err) {
        this.error = 'Failed to load courses'
        this.loading = false
        console.error(err)
      }
    },

    async continueStudy(course) {
      try {
        // Get lessons for the course to find the next incomplete lesson
        const lessons = await http.get(`/courses/${course.id}/lessons`)

        // Get progress for all lessons in this course
        const lessonProgress = await http.get(`/progress/lessons?course_path=${course.path}`)

        // Create a map of lesson progress by lesson path
        const progressMap = {}
        lessonProgress.forEach(progress => {
          progressMap[progress.lesson_path] = progress
        })

        // Find the first lesson that is not completed
        let nextLesson = null
        for (const lesson of lessons) {
          const progress = progressMap[lesson.path]
          if (!progress || progress.completion_percentage < 100) {
            nextLesson = lesson
            break
          }
        }

        // If all lessons are completed, use the first lesson
        if (!nextLesson && lessons.length > 0) {
          nextLesson = lessons[0]
        }

        // Navigate to the lesson if found
        if (nextLesson) {
          this.$router.push(`/lesson/${encodeURIComponent(nextLesson.path)}`)
        }
      } catch (err) {
        console.error('Error finding next lesson:', err)
        // Fallback to course page
        this.$router.push(`/course/${course.id}`)
      }
    }
  }
}
</script>

<style scoped lang="scss">
@use "../assets/styles/home";
</style>